package com.admin.controller;


import cn.hutool.core.io.FileUtil;
import com.admin.entity.Admin;
import com.admin.entity.Apk;
import com.admin.entity.Theme;
import com.admin.service.IAdminService;
import com.admin.service.IApkService;
import com.admin.service.IThemeService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.OssUpload;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.token.JwtUtil;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author marisheng
 * @since 2019-11-21
 */
@RestController
@RequestMapping("/admin/apk")
public class ApkController {


    @Autowired
    private IApkService apkService;

    private long lastAddApk ;

    @Value("${upload.tmp.dir}")
    private String tmp;

    @Value("${upload.dir}")
    private String upload;

    @Autowired
    private IAdminService adminService;


    @Autowired
    HttpServletRequest request;

    @Autowired
    private OssUpload ossUpload;

    @Autowired
    private IThemeService  themeService;

    /**
     * 查询:统计普通apk被访问次数（柱状统计图）
     *
     * @return
     */
    @GetMapping
    @RequestMapping(value = "/searchApkWithVisit", method = RequestMethod.GET)
    public ResponseBean searchApkWithVisit() {
        List list = apkService.list();
        if (list != null) {
            return new ResponseBean(200, "操作成功", list);
        }
        return new ResponseBean(500, "操作失败", list);
    }

    /**
     * 查询普通Apk 以及根据条件查询
     *
     * @param page
     * @param limit
     * @param
     * @param map
     * @return
     */


    @RequestMapping("/searchApkWithPageById")
    public ResponseBean searchApkWithPageById(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, String token, @RequestParam Map map) {

        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (admin == null) {
            return new ResponseBean(401, "没有登录", null);
        }
        int adminId = admin.getAdminId();
        IPage result = apkService.searchApkWithPageById(page, limit, adminId, map);
        return new ResponseBean(0, result.getTotal(), result.getRecords());
    }

    /**
     * 新增普通apk应用
     *
     * @param apk
     * @return
     */
    @RequestMapping(value = "/addApk", method = RequestMethod.POST)
    public ResponseBean addApk(Apk apk) {

        long now = System.currentTimeMillis();
        if (now-lastAddApk<1000){
            return new ResponseBean(401,"频繁操作","");
        }
        lastAddApk = now;


        String token = request.getHeader("token");
        String username = JwtUtil.getUsername(token);
        //截取得到文件名 //d:/tmp/1xxx.apk
        String oldPath = apk.getApkUrl();
        File file = new File(oldPath);
        String name = file.getName();


        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        File newPath1 = new File(upload + "/apk/apk/" + date);
        if (newPath1.exists() == false) {
            newPath1.mkdirs();
        }

        File newPath2 = new File(upload + "/apk/images/" + date);
        if (newPath2.exists() == false) {
            newPath2.mkdirs();
        }

        String oldPicture = apk.getApkPictureUrl();
        apk.setApkPictureUrl("/upload/apk/images/" + date + "/" + oldPicture);
        apk.setApkUrl("/upload/apk/apk/" + date + "/" + name);

        int insert = apkService.addApk(apk, username);

        if (insert > 0) {

            //将图片从临时目录复制到正式目录
            FileUtil.copy(tmp + "/" + oldPicture, upload + "/apk/images/" + date + "/" + oldPicture, true);
            //将apk应用文件从临时目录复制到正式目录
            FileUtil.copy(tmp + "/" + name, upload + "/apk/apk/" + date + "/" + name, true);

            //上传到oss
            ossUpload.upload("/upload/apk/apk/" + date + "/" + name, new File(newPath1 + "/" + name));

            return new ResponseBean(200, "新增成功", "");
        }
        return new ResponseBean(500, "新增失败", "");
    }


    /**
     * 是否有权限编辑
     *
     * @param adminTr
     * @param token
     * @return
     */
    @RequestMapping(value = "/isItQuanxian", method = RequestMethod.POST)
    public ResponseBean isItQuanxian(int adminTr, String token) {
        String username = JwtUtil.getUsername(token);
        if (apkService.findAdminByPhone(username) == null) {
            return new ResponseBean(500, null, "没有权限");
        }
        return new ResponseBean(200, null, null);
    }


    /**
     * 根据主键修改普通apk
     *
     * @param apk
     * @return
     */
    @RequestMapping(value = "/updateApkByApkId")
    public ResponseBean updateApkByApkId(Apk apk) {
        String username = JwtUtil.getUsername(request.getHeader("token"));
        Admin admin = apkService.findAdminByPhone(username);
        if (apk == null) {
            return new ResponseBean(0, "参数错误", null);
        }
        Apk newApk = apkService.getById(apk.getApkId());

        String apkFileName = null;


        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        File newPath1 = new File(upload + "/apk/apk/" + date);
        if (newPath1.exists() == false) {
            newPath1.mkdirs();
        }

        File newPath2 = new File(upload + "/apk/images/" + date);
        if (newPath2.exists() == false) {
            newPath2.mkdirs();
        }

        //修改了apk

        newApk.setApkIsItPublic(apk.getApkIsItPublic());
        newApk.setApkName(apk.getApkName());
        newApk.setApkShenhe(apk.getApkShenhe());
        if (StringUtil.isNotNull(apk.getApkUrl())) {
            File apkFile = new File(apk.getApkUrl());
            apkFileName = apkFile.getName();
            newApk.setApkPackage(apk.getApkPackage());
            newApk.setApkMd5(apk.getApkMd5());
            newApk.setApkUrl("/upload/apk/apk/" + date + "/" + apkFileName);
            newApk.setApkVersion(apk.getApkVersion());

        }

        String apkPackage = apk.getApkPackage();
        if (apkPackage!=null && apkPackage.equals(newApk.getApkPackage())==false){
            newApk.setApkPackage(apk.getApkPackage());
        }

        //修改了图片
        boolean updatePic = false;
        if (StringUtil.isNotNull(apk.getApkPictureUrl()) && apk.getApkPictureUrl().equals(newApk.getApkPictureUrl()) == false) {
            updatePic = true;
            newApk.setApkPictureUrl("/upload/apk/images/" + date + "/" + apk.getApkPictureUrl());

        }


        //截取得到文件名
        boolean f = apkService.updateById(newApk);
        if (f) {
            //将文件从临时目录复制到正式目录
            if (updatePic) {
                FileUtil.copy(tmp + "/" + apk.getApkPictureUrl(), upload + "/apk/images/"+date+"/" + apk.getApkPictureUrl(), true);
            }

            if (StringUtil.isNotNull(apk.getApkUrl())) {
                //将apk应用文件从临时目录复制到正式目录
                FileUtil.copy(tmp + "/" + apkFileName, upload  +"/apk/apk/"+date+"/"+apkFileName, true);

                //上传到oss
                ossUpload.upload(newApk.getApkUrl(), new File(upload + "/apk/apk/"+date+"/"+apkFileName));
            }

            //同步所有桌面apk
            List<Theme> themeList = themeService.list();
            for (Theme t: themeList){
                /*String android      = t.getThemeAuditAndroidAudited();
                JSONObject jsonObject =  JSONObject.parseObject(android);
                JSONArray  jsonArray = jsonObject.getJSONObject("data").getJSONObject("CN").getJSONObject("desktop").getJSONObject("main").getJSONObject("data").getJSONObject("content").getJSONArray("info");
                int size = jsonArray.size();
                for (int i=0;i<size;i++){
                    JSONObject jsonObjectItem = jsonArray.getJSONObject(i);
                    String packageName = jsonObjectItem.getString("packageName");
                    String apkUrl   = jsonObjectItem.getString("apk");


                }*/

            }



            return new ResponseBean(200, "编辑成功", null);
        }
        return new ResponseBean(500, "编辑失败", null);
    }


    /**
     * 根据主键修改是否公开
     *
     * @param map
     * @return
     */
    @PostMapping("/updateApkByApkIdWithPublic")
    public ResponseBean updateApkByApkIdWithPublic(@RequestParam Map map) {
        if (map == null) {
            return new ResponseBean(0, null, null);
        }
        Apk apk = apkService.getById((String) map.get("data[apk_id]"));
        if ("公开".equals(apk.getApkIsItPublic())) {
            apk.setApkIsItPublic("不公开");
        } else {
            apk.setApkIsItPublic("公开");
        }
        boolean f = apkService.updateById(apk);
        int code = f ? 200 : 500;
        return new ResponseBean(code, null, apk);
    }


    /**
     * 更新主题中所有apk
     *
     * @return
     */
    @RequestMapping("/update")
    public ResponseBean update(@RequestParam String apkId) {
        if (apkId == null) {
            return new ResponseBean(0, null, null);
        }

        Admin admin =(Admin) request.getSession().getAttribute("admin");
        if (admin==null || admin.getAdminParent()!=0){
            return new ResponseBean(201, "没有权限", null);
        }

        Apk apk = apkService.getById(apkId);
        boolean f  = apkService.updateAllStationByApk(apk);
        int code = f ? 200 : 500;
        return new ResponseBean(code, null, apk);
    }




    /**
     * 根据主键删除普通apk
     *
     * @param apkId
     * @return
     */
    @RequestMapping(value = "/deleteApkByApkId", method = RequestMethod.POST)
    public ResponseBean deleteApkByApkId(int apkId) {
        boolean f = apkService.removeById(apkId);
        int code = f ? 200 : 500;
        return new ResponseBean(code, null, null);
    }


    /**
     * 修改apk的状态
     *
     * @param apk
     * @return
     */
    @RequestMapping("/updataApkShenhe")
    public ResponseBean updataApkShenhe(Apk apk) {
        apk.setApkShenhe("已审核");
        boolean f = apkService.updateById(apk);
        int code = f ? 200 : 500;
        return new ResponseBean(code, null, null);
    }

    /**
     * 查所有未审核的apk
     *
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/selApkShehe")
    public ResponseBean selApkShenhe(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit) {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (admin == null) {
            return new ResponseBean(401, "没有登录", null);
        }

        IPage iPage = apkService.apkShenhe(page, limit,admin);
        return new ResponseBean(0, iPage.getTotal(), iPage.getRecords());
    }


}
